package com.shensi.adminCollect.service.markert.impl;

import cn.hutool.core.convert.Convert;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.domain.coupon.CouponUser;
import com.shensi.adminCollect.service.coupon.ICouponUserService;
import com.shensi.adminCollect.domain.markert.vo.YunHuaOrderVo;
import com.shensi.adminCollect.service.markert.YunHuaOrderService;
import com.shensi.adminCollect.domain.station.*;
import com.shensi.adminCollect.mapper.station.*;
import com.shensi.adminCollect.mapper.system.SysUserMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;



@Service
public class YunHuaOrderServiceImpl implements YunHuaOrderService {

    @Resource
    private OilMapper oilMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Resource
    private ICouponUserService couponUserService;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Resource
    private EnterpriseMapper enterpriseMapper;


    @Override
    public AjaxResult insertPayOrderForYunHua(YunHuaOrderVo yunHuaOrderVo) {

        PayOrder payOrder = new PayOrder();
        payOrder.setOutOrderNo(yunHuaOrderVo.getOutOrderNo());
        payOrder.setStationId(Long.valueOf(yunHuaOrderVo.getStationId()));
        Station station = stationMapper.selectStationById(Long.valueOf(yunHuaOrderVo.getStationId()));
        payOrder.setStationName(station.getStationName());
        payOrder.setStatus(yunHuaOrderVo.getStatus());
        Oil oil = oilMapper.selectOilByName(yunHuaOrderVo.getOilName());
        if (oil != null) {
            payOrder.setOilName(oil.getOilId().toString());
        }

        payOrder.setEnterpriseId(station.getEnterpriseId());
        Enterprise enterprise = enterpriseMapper.selectEnterpriseById(station.getEnterpriseId());
        payOrder.setEnterpriseName(enterprise.getEnterpriseName());

        payOrder.setOilPirce(new BigDecimal(yunHuaOrderVo.getOilPrice()));

        payOrder.setOrderType("1".equals(yunHuaOrderVo.getOilType()) ? "柴油" : "汽油");
        payOrder.setOrderLiters(new BigDecimal(yunHuaOrderVo.getOrderLiters()));
        payOrder.setReceivableAmt(yunHuaOrderVo.getReceiveableAmt());
        payOrder.setAmt(yunHuaOrderVo.getAmt());
        payOrder.setPlatformDiscount(yunHuaOrderVo.getPlatformDiscount().toString());
        payOrder.setDiscountAmt(yunHuaOrderVo.getReductionAmt());
        if(Objects.nonNull(yunHuaOrderVo.getDiscountCoupon())){
            payOrder.setDiscountCoupon(yunHuaOrderVo.getDiscountCoupon().toString());
        }

        payOrder.setDiscountCouponAmt(yunHuaOrderVo.getCouponAmt());
        payOrder.setPayDate(Convert.toDate(yunHuaOrderVo.getPayDate(),new Date()));
        payOrder.setCreatedDate(Convert.toDate(yunHuaOrderVo.getCreatedDate(),new Date()));
        payOrder.setCustomerPhone(yunHuaOrderVo.getCustomerPhone());
        //云化订单
        payOrder.setUtmSource("3");
        //查询用户信息
        HashMap<String, Object> selectMap = new HashMap<>();
        selectMap.put("mobilePhone",yunHuaOrderVo.getCustomerPhone());
        selectMap.put("stationId",station.getEnterpriseId());
        List<SysAppUserInfo> sysAppUserInfos = appUserInfoMapper.selectAppUserInfoByPhoneAndStationId(selectMap);
        if(CollectionUtils.isNotEmpty(sysAppUserInfos)){
            payOrder.setConsumerId(sysAppUserInfos.get(0).getUserId());
        }

        //退款
        if("3".equals(payOrder.getStatus())){
            //修改订单状态
            PayOrder payOrderRes = payOrderMapper.selectOrderByOutOrderNo(yunHuaOrderVo.getOutOrderNo());
            if(Objects.isNull(payOrderRes)){
                return AjaxResult.error("订单不存在");
            }

            PayOrder payOrderUpdate = new PayOrder();
            payOrderUpdate.setOrderNo(payOrderRes.getOrderNo());
            payOrderUpdate.setStatus("3");
            payOrderUpdate.setRefundDate(new Date());
            payOrderMapper.updatePayOrderByOrderNo(payOrderUpdate);

            //修改优惠券状态
            if(StringUtils.isNotEmpty(payOrder.getDiscountCoupon())){
                couponUserService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).id(Integer.valueOf(payOrder.getDiscountCoupon())).couponIsUsed("0").build());
            }

            return AjaxResult.success("同步退款订单成功");
        }else if("1".equals(payOrder.getStatus())){
            PayOrder payOrderRes = payOrderMapper.selectOrderByOutOrderNo(yunHuaOrderVo.getOutOrderNo());
            if(Objects.nonNull(payOrderRes)){
                return AjaxResult.success("订单同步成功");
            }


            String ordNo = generateOrdNo();
            payOrder.setOrderNo(ordNo);
            //3为云化的订单
            payOrder.setUtmSource("3");

            payOrder.setOilPersonnelId("yunhua");

            int a = payOrderMapper.insertPayOrder(payOrder);

            if(Objects.nonNull(payOrder.getDiscountCoupon())){
                couponUserService.updateCouponUser(CouponUser.builder().verificationTime(new Date()).id(Integer.valueOf(payOrder.getDiscountCoupon())).couponIsUsed("1").build());
            }

            //打印小票
//        printStarOrder(payOrder, sysuser);
            if (a > 0) {
                return AjaxResult.success("同步订单成功", ordNo);
            } else {
                return AjaxResult.error("新增失败");
            }
        }

            return AjaxResult.success("同步订单成功");

    }

    private String generateOrdNo() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }
}
